package com.ly.index.web;

import com.ly.bean.Result;
import com.ly.damai.entity.Product;
import com.ly.damai.entity.User;
import com.ly.index.web.feign.OtherAction;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class IndexDo {

    @Autowired
    OtherAction otherAction;

    Map<String,Object> cache = new HashMap<>();
    public Map<String, Object> getCache() {
        return cache;
    }

    @RequestMapping("hots")
    List<Product> queryHots(){
        List<Product> products = otherAction.queryHots();
        if(cache.containsKey("hots") == false){
            // TODO 考虑如何刷新 => 定时任务
            cache.put("hots",products);
        }
        return products;
    }




    ///////////////////////////////////////////////////
    @RequestMapping("index")
    String index(HttpServletRequest request) {
        return "index " + request.getServerPort();
    }

    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("index-other")
    String other(){
        return restTemplate.getForObject("http://cloud-other/other", String.class);
    }

    @RequestMapping("add")
    // 服务端
    int add(@RequestParam("a") int a,
            @RequestParam("b") int b) {
        return otherAction.add(a, b);
    }

    // 对象属性映射为请求参数名, 自动装箱
    @RequestMapping("res")
    Result res(Result result) {
        return otherAction.res(result);
    }

    // 用户信息是通过 请求体 body 传递过来
    @RequestMapping("user")
    User user(@RequestBody User user,
              @RequestParam("myname") String myname){
        return otherAction.user(user, myname);
    }

    // RESTful 请求方式的地址参数
    @RequestMapping("/hello/{nm}")
    String hello(@PathVariable("nm") String name) {
        return otherAction.hello(name);
    }

}
